<template>
  <div class="users">
    <!-- 路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框部分 -->
    <el-input placeholder="请输入搜索关键字" v-model="query" class="input-with-select">
      <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <el-button @click="addVisible = true" type="success" plain>添加用户</el-button>
    <!-- 表格部分 -->
    <el-table :data="userList" border>
      <el-table-column prop="username" label="姓名" width="180px"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180px"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="180px"></el-table-column>
      <el-table-column prop="date" label="用户状态" width="100px">
        <template v-slot:default="{ row }">
          <el-switch
            @change="changeStatus(row.id, row.mg_state)"
            v-model="row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template v-slot:default="{ row }">
          <el-button @click="showEdit(row)" type="primary" size="small" plain icon="el-icon-edit"></el-button>
          <el-button
            @click="delUser(row.id)"
            type="danger"
            size="small"
            plain
            icon="el-icon-delete"
          ></el-button>
          <el-button @click="showAssign(row)" type="success" size="small" plain icon="el-icon-check">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 3, 4, 5, 6]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加用户框 -->
    <el-dialog title="添加用户" :visible.sync="addVisible" width="40%">
      <el-form :rules="rules" ref="addForm" :model="addForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户框 -->
    <el-dialog title="修改用户" :visible.sync="editVisible" width="40%">
      <el-form :rules="rules" ref="editForm" :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-tag type="info">{{ editForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <div class="con-footer">
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="assignVisible" width="40%">
      <el-form :rules="rules" ref="assignForm" :model="assignForm" label-width="80px">
        <el-form-item label="用户名">
          <el-tag type="info">{{ assignForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-select v-model="assignForm.rid" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="con-footer">
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignRole">分 配</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      query: '',
      pagenum: 1,
      pagesize: 2,
      userList: [],
      total: 0,
      addVisible: false,
      editVisible: false,
      assignVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      assignForm: {
        id: '',
        rid: '',
        username: ''
      },
      roleList: [],
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 发送ajax请求获取数据
    async getUserList () {
      const { meta, data } = await this.$axios.get('users', {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        this.userList = data.users
        this.total = data.total
        // console.log(this.userList)
      } else {
        console.log(meta.msg)
      }

      // this.$axios
      //   .get('users', {
      //     params: {
      //       query: this.query,
      //       pagenum: this.pagenum,
      //       pagesize: this.pagesize
      //     }
      //   })
      //   .then(res => {
      //     // console.log(res)
      //     const { meta, data } = res
      //     if (meta.status === 200) {
      //       this.userList = data.users
      //       this.total = data.total
      //       // console.log(this.userList)
      //     }
      //   })
    },
    // 改变页面数据个数
    handleSizeChange (val) {
      this.pagesize = val
      this.pagenum = 1
      this.getUserList()
    },
    // 改变当前页
    handleCurrentChange (val) {
      this.pagenum = val
      this.getUserList()
    },
    // 用户搜索功能
    searchUser () {
      this.pagenum = 1
      this.getUserList()
    },
    // 改变状态
    async changeStatus (id, status) {
      const { meta } = await this.$axios.put(`users/${id}/state/${status}`)
      if (meta.status === 200) {
        this.$message.success('修改成功')
      } else {
        this.$message.error(meta.msg)
      }
      // this.$axios.put(`users/${id}/state/${status}`).then(res => {
      //   const { meta } = res
      //   if (meta.status === 200) {
      //     this.$message.success('修改成功')
      //   } else {
      //     this.$message.error(meta.msg)
      //   }
      // })
    },
    // 删除用户
    async delUser (id) {
      try {
        await this.$confirm('你确定要删除吗', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          if (this.userList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          console.log(meta.msg)
        }
      } catch (e) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 添加用户
    async addUser () {
      try {
        await this.$refs.addForm.validate()
        const { meta } = await this.$axios.post('users', this.addForm)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.$refs.addForm.resetFields()
          this.addVisible = false
          this.total++
          this.pagenum = Math.ceil(this.total / this.pagesize)
          this.getUserList()
        } else {
          console.log(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 显示编辑用户框
    showEdit (row) {
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editVisible = true
    },
    // 编辑用户
    async editUser () {
      const { meta } = await this.$axios.put(`users/${this.editForm.id}`, this.editForm)
      console.log(meta)

      if (meta.status === 200) {
        this.$message.success('更新成功')
        this.editVisible = false
        this.getUserList()
      } else {
        console.log(meta.msg)
      }
    },
    // 显示分配角色框
    async showAssign (row) {
      this.assignForm.id = row.id
      this.assignForm.username = row.username
      this.assignVisible = true
      // 角色 id, rid 也要回显, 发送请求
      const resUser = await this.$axios.get(`users/${row.id}`)
      if (resUser.meta.status === 200) {
        const rid = resUser.data.rid
        // 如果是新添加的用户, 给 ''
        this.assignForm.rid = rid === -1 ? '' : rid
      }
      // 渲染所有角色
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.roleList = data
        // console.log(data)
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 分配角色
    async assignRole () {
      const { id, rid } = this.assignForm
      if (!rid) return this.$message.error('请选择角色')
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.assignVisible = false
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.users {

  .input-with-select {
    width: 300px;
    margin-bottom: 10px;
    margin-right: 20px;
  }
  .con-footer {
    text-align: right;
  }
}
</style>
